package com.wei.duowan.bbs.utils;

import android.content.res.AssetManager;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.wei.duowan.bbs.App;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 作者：赵若位
 * 时间：2019/7/31 23:28
 * 联系方式：1070138445
 * 功能：字符串相关操作类
 */
public class StringUtils
{
    private static final String TAG = StringUtils.class.getSimpleName();


    /*头条详情获取文章内容*/
    public static List<String> getArticleContent(@Nullable String content)
    {
        if (!TextUtils.isEmpty(content))
        {
            List<String> list = new ArrayList<>();
            if (content.contains("[url=") && content.contains("[/url]"))
            {
                content = content.replaceAll("\\[url=", "[/p][p][url=");
            }
            Pattern p = Pattern.compile("\\[p.*?].+?\\[/p]|\\[img.*?].+?\\[/img]");
            Matcher m = p.matcher(content);
            while (m.find())
            {
                String str = m.group();
                Log.e(TAG, "getArticleContent: " + str);
                if (!TextUtils.isEmpty(str))
                {
                    list.add(str);
                }
            }
            return list;
        }
        return null;
    }



    /**
     * 从assets文件夹中获取json文件
     *
     * @param fileName
     * @return
     */
    public static String getAssetsJson(@Nullable String fileName)
    {
        //将json数据变成字符串
        StringBuilder builder = new StringBuilder();
        try
        {
            //获取assets资源管理器
            AssetManager assetManager = App.getContext().getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null)
            {
                builder.append(line);
            }
        } catch (IOException e)
        {
            Log.e(TAG, "getDataFromAssets: " + e.getMessage());
            return null;
        }
        return builder.toString();
    }

}
